package git.soulbgm.monitor;

import git.soulbgm.utils.LogHelper;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ZooKeeper监控
 *
 * @author SoulBGM
 * @date 2025-01-16
 */
public class ZooKeeperMonitor {

    private static final LogHelper LOG = new LogHelper(ZooKeeperMonitor.class);
    private static Map<String, Integer> zkServerMap;

    public static void setZkServers(String zkServers) {
        String[] split = zkServers.split(",");
        zkServerMap = Arrays.stream(split).map(o -> o.split(":")).collect(Collectors.toMap(o -> o[0], o -> Integer.parseInt(o[1]), (o1, o2) -> o1, LinkedHashMap::new));
    }

    public static Map<String, String> getPerformanceInfoMap() {
        if (zkServerMap == null || zkServerMap.isEmpty()) {
            return Collections.emptyMap();
        }
        Map<String, String> performanceInfoMap = new LinkedHashMap<>(zkServerMap.size());
        zkServerMap.forEach((ip, port) -> {
            String key = ip + ":" + port;
            try (Socket socket = new Socket(ip, port);
                 OutputStream outputStream = socket.getOutputStream();
                 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
                 PrintWriter out = new PrintWriter(outputStreamWriter, true);
                 InputStream inputStream = socket.getInputStream();
                 InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                 BufferedReader in = new BufferedReader(inputStreamReader)
            ) {
                out.println("srvr");
                StringBuilder responseContent = new StringBuilder();
                String response = in.readLine();
                while (response != null) {
                    responseContent.append(response).append("\n");
                    response = in.readLine();
                }
                performanceInfoMap.put(key, responseContent.toString());
            } catch (Exception e) {
                LOG.error("访问ZooKeeper {} 节点出现异常", key, e);
                performanceInfoMap.put(key, null);
            }
        });
        return performanceInfoMap;
    }

    public static void main(String[] args) {
        setZkServers("192.168.10.21:2181");
        final Map<String, String> map = getPerformanceInfoMap();
        System.out.println(map);
    }

}
